import { useState, useCallback } from 'react'
import { useRequest, useUpdateEffect } from 'ahooks';
import { useConfigEventsApi } from '../../../../../store/hooks/useSearchPropsState';
import { useSearchUIState } from '../../../../../store/hooks/useSearchUIState';
import { useAssociativeWords } from '../../../../../store/hooks/useAssociativeWords';
import { useEcmSearchLocation } from './useEcmSearchLocation';
import { useFetchHistoryData } from './useFetchHistoryData'
import {
  getSynonymWord,
} from '../../../../../designer/service';
// 历史搜索记录,搜索相关内容
export const useSearchDataSource = (action: ReturnType<typeof useFetchHistoryData>) => {
  const { configEventsApi } = useConfigEventsApi();
  const { ecmSearchType, selectShowTab } = useSearchUIState();
  const searchLocation = useEcmSearchLocation();
  const { fetchHistoryData } = action;
  // 搜索推荐
  const [searchDataSource, setSearchDataSource] = useState<string[]>([]);
  const associativeWords = useAssociativeWords();

  const { data, run, cancel } = useRequest(
    (params) =>
      configEventsApi({
        request: getSynonymWord,
        params,
        keys: ['onSearchKeyWordParams', 'onSearchKeyWord', 'onSearchKeyWordData'],
      }),
    {
      manual: true,
      debounceWait: 300, // 节流
    },
  );
  useUpdateEffect(() => {
    setSearchDataSource(data || []);
  }, [data]);

  const fetchSearchDataSource = useCallback(
    async (keyword: string) => {
      // 是否开启联想词
      if (!associativeWords) return;
      if (!keyword) {
        // 没有输入关键字的时候，显示历史搜索
        fetchHistoryData();
      } else {

        // 输入关键字的时候，显示联想词
        if (selectShowTab?.isAll) {
          // 全部 没得索引库，就不显示联想词
          setSearchDataSource((prev) => (prev.length ? [] : prev));
        } else {
          // 非全部类型
          const params = {
            IndexName: selectShowTab?.isDMS
              ? ecmSearchType?.includes(4)
                ? 'folder'
                : 'file'
              : selectShowTab?.indexLibraries?.[0].IndexName || '', // 索引库名
            KeyWord: keyword, // 关键字
            Size: 10,
            SearchWhere: '',
          };
          run(params);
        }
      }
    },
    [ecmSearchType, associativeWords, selectShowTab, searchLocation, fetchHistoryData],
  );
  const clear = useCallback(() => {
    setSearchDataSource([])
  }, [])


  return {
    searchDataSource,
    fetchSearchDataSource,
    clear,
    cancel
  };
};
